package com.project.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //取出session中保存的登录信息
        HttpServletRequest req = (HttpServletRequest) servletRequest;

        Object loginObj = req.getSession().getAttribute("userName");

        HttpServletResponse resp = (HttpServletResponse)servletResponse;
        if (loginObj == null){
            //重定向到登陆页面
            resp.sendRedirect("/html/login.html");
        }
        else {
            //请求通过过滤器，继续访问目标资源
            filterChain.doFilter(req,resp);
        }
    }
}
